#include "DXDevice.h"

DXDevice::DXDevice (void)
{
}

DXDevice::DXDevice (Window & GameWindow)
{
	Init(GameWindow);
}

DXDevice::~DXDevice (void)
{
	CleanD3D();
}

BOOL DXDevice::Init (Window & GameWindow)
{
	ClearColor = COLOR(0, 0, 0, 0);
	return InitD3D(GameWindow);
}

void DXDevice::BeginRendering (void)
{
	Clear();
	d3ddev->BeginScene();
}

void DXDevice::BeginSprite (void)
{
	d3dspt->Begin(NULL);
}

void DXDevice::EndSprite (void)
{
	d3dspt->End();
}

void DXDevice::EndRendering (void)
{
	d3ddev->EndScene();
	d3ddev->Present(NULL, NULL, NULL, NULL);
}

void DXDevice::Clear (void)
{
	d3ddev->Clear(0, NULL, D3DCLEAR_TARGET, ClearColor, 1.0f, 0);
	d3ddev->Clear(0, NULL, D3DCLEAR_ZBUFFER, ClearColor, 1.0f, 0);
}

void DXDevice::SetClearColor (int Red, int Green, int Blue, int Alpha)
{
	ClearColor = D3DCOLOR_RGBA(Red, Green, Blue, Alpha);
}


LPDIRECT3DDEVICE9 DXDevice::GetDrawDevice (void)
{
	return d3ddev;
}

LPDIRECT3D9 DXDevice::GetDirectXDevice (void)
{
	return d3d;
}

LPD3DXSPRITE DXDevice::GetSpriteDevice (void)
{
	return d3dspt;
}

BOOL DXDevice::InitD3D (Window & GameWindow)
{
	BOOL Success = TRUE;

	//DirectX Initialization
	d3d = Direct3DCreate9(D3D_SDK_VERSION);
	
	D3DPRESENT_PARAMETERS d3dpp;
	ZeroMemory(&d3dpp, sizeof(d3dpp));
	d3dpp.Windowed = !GameWindow.FullScreen;
	d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
	d3dpp.hDeviceWindow = GameWindow.hWnd;
	d3dpp.EnableAutoDepthStencil = TRUE;
	d3dpp.AutoDepthStencilFormat = D3DFMT_D16;
	d3dpp.BackBufferFormat = D3DFMT_X8R8G8B8;
	d3dpp.BackBufferWidth = GameWindow.ScreenWidth;
	d3dpp.BackBufferHeight = GameWindow.ScreenHeight;

	d3d->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, GameWindow.hWnd,
					  D3DCREATE_SOFTWARE_VERTEXPROCESSING, &d3dpp, &d3ddev);

	if (!d3ddev)
		Success = FALSE;
	else
	{	
		d3ddev->SetRenderState(D3DRS_LIGHTING, FALSE);
		d3ddev->SetRenderState(D3DRS_ZENABLE, TRUE);
	}
	
	D3DXCreateSprite(d3ddev, &d3dspt);
	if (!d3dspt)
		Success = FALSE;

	return Success;
}

void DXDevice::CleanD3D (void)
{
	if (d3dspt)
		d3dspt->Release();
	if (d3ddev)
		d3ddev->Release();
	if (d3d)
		d3d->Release();
}